<!DOCTYPE html>
<html>
<head>
<title>Quick Stock Watch</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="imagex-icon" href="favicon.ico">
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<style>
	body {
		padding: 5px;
	}
	.separator {
		margin-left: 5px;
	}
</style>
</head>
<body>
	<!--  
	<div id="adContent2" style="height:60px">
		<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
		QSW-Gadget Ad
		<ins class="adsbygoogle"
		     style="display:inline-block;width:468px;height:60px"
		     data-ad-client="ca-pub-9983113299815649"
		     data-ad-slot="3581915552"></ins>
		<script>
		(adsbygoogle = window.adsbygoogle || []).push({});
		</script>
		<script type="text/javascript">
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', 'UA-1214589-5']);
		  _gaq.push(['_trackPageview']);
		  (function() {
		    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		  })();
		</script>
	</div>
	-->
	<a href="#settingsModal" class="btn btn-small pull-right" data-toggle="modal" id="settingsloadbtn" style="margin-left:5px"><i class="icon-cog"></i> Settings</a>
	<a href="http://udaysasi-gadgets.googlecode.com/svn/trunk/quickStockWatch.html" class="btn btn-small pull-right" target="newwin" id="fullscreen"><i class="icon-fullscreen"></i> FullScreen</a>
	<div class="clearfix"></div>
	<div class="clearfix alert hide" id="message" style="margin-bottom:0px;padding:2px;">
		<small>Temporary fix has been put in place for Internet Explorer users. Permanent fix coming soon.</small>  
	</div>  
	<div id="watchListContent" class="contentData clearfix">
		<table class="table table-condensed table-striped">
			<thead>
				<tr>
					<th>&nbsp;</th>
					<th>Sym</th>
					<th class="namer">Name</th>
					<th>Price</th>
					<th>Change</th>
					<th>% Change</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td colspan="6" style="text-align:center">Loading your watchlist..</td>
				</tr>
			</tbody>
		</table>
	</div>
	<div id="portfolioContent" style="display:none;width:100%" class="clearfix">Loading your portfolio. Please wait...</div>
	
	<div id="adContent" style="height:60px">
		<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
		<ins class="adsbygoogle"
		     style="display:inline-block;width:468px;height:60px"
		     data-ad-client="ca-pub-9983113299815649"
		     data-ad-slot="3581915552"></ins>
		<script>
		(adsbygoogle = window.adsbygoogle || []).push({});
		</script>
		<script type="text/javascript">
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', 'UA-1214589-5']);
		  _gaq.push(['_trackPageview']);
		  (function() {
		    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		  })();
		</script>
		<!--  
		<iframe id="ad0" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=subscribe&banner=00ZH4W1WT6HQDHJXFV02&f=ifr&linkID=S6TGB4GDPEHZBLXV" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad1" class="hide" src="//z-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetAdHtml&ID=OneJS&OneJS=1&banner_type=setandforget&campaigns=holsetforget2&placement=assoc_banner_placement_default&region=US&marketplace=amazon&tracking_id=udaysasi-20&ad_type=banner&height=60&width=468&linkid=NYW3FNDH6U5PIT6T&f=ifr" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad2" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=ce_wearabletech&banner=1RPTSCBFWA8PHN5C7QG2&f=ifr&linkID=KDPMPBFE4YN7ZEQN" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad3" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=cctrade&banner=0KZK3C7S18PE82KK4Z82&f=ifr&linkID=E3FZYBBOARKCMDUE" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad4" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=topgiftideas&banner=13TF8DHM5H3K11P61YR2&f=ifr&linkID=GY3AULAQ4K7YU62O" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad5" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=mostwishforitem&banner=1M2GXANPMRX5Z7KV4202&f=ifr&linkID=VII7PWTWOCG46XV3" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad6" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=sh48_421_5070off&banner=0R1RH6Z4PEX3MT1GMH02&f=ifr&linkID=XW4C2WFH3DPL37JW" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad7" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=bestsellingproducts&banner=1F8VTV49P7N5K5XY5N82&f=ifr&linkID=HK7TXPB6IUPGZLEL" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad8" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=maythefourth&banner=1CGX58KRBW7XR4XP2002&f=ifr&linkID=GTZVT2U7BH2UDF3V" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		<iframe id="ad9" class="hide" src="//rcm-na.amazon-adsystem.com/e/cm?t=udaysasi-20&o=1&p=26&l=ur1&category=home_mdaygifts_15&banner=03VDGE48BKQW34K768G2&f=ifr&linkID=4R4RZDTMW2ZVN2AH" width="468" height="60" scrolling="no" border="0" marginwidth="0" style="border:none;" frameborder="0"></iframe>
		-->
	</div>
	
	<form class="form-inline">
		<a class="separator" href="#" id="strengthbtn">Strength</a>
		<a class="separator" href="#" id="newsbtn">News</a>
		<a class="separator" href="#" id="view">Portfolio</a>
		<a class="separator" href="#" id="profitChart">ProfitChart</a>
		<a class="separator" href="#" id="emailbtn">Email</a>
		<a class="separator" href="http://udaysasi-gadgets.googlecode.com/svn/trunk/quickStockWatchHelp.html"  target="quickstockwatchhelp">Help</a>
		<a class="separator" href="http://groups.google.com/group/quickstockwatch" target="grouppage">Discuss</a>
		<a class="separator" href="mailto:udaysasi+feedback@gmail.com" target="emailpage">Feedback</a>
		<a class="separator" href="#" id="problememail">Problems?</a>
	</form>
	<div id="myContainer"></div>
	<div id="newsContent"></div>
	<table width="99%" id="strengthContent" style="display:none">
		<tbody>
		<tr>
			<td style="width:100%">
				<table style="align:center" border="0" cellpadding="0" cellspacing="0" width="100%">
					<tbody>
					<tr style="height:15px">
						<td id="n59" style="background-color: #992020;width:0%" title=""></td>
						<td id="n25" style="background-color: #CC4949;width:0%" title=""></td>
						<td id="n02" style="background-color: #FF8383;width:0%" title=""></td>
						<td id="p02" style="background-color: #83FF83;width:0%" title=""></td>
						<td id="p25" style="background-color: #49CC49;width:0%" title=""></td>
						<td id="p59" style="background-color: #209920;width:0%" title=""></td>
					</tr>
					</tbody>
				</table>
			</td>
		</tr>
		</tbody>
	</table>
	<div id="chartContent" style="align:center;border:1px solid #FFFFFF; width:95%; display:none; font-family: arial,sans-serif;">Loading your profit chart.. Please wait..</div>
	<hr id="chartHorLine" style="display:none;width:99%"/>
	
	<div id="emailContent" style="align:left;border:1px solid #FFFFFF; width:99%; display:none; font-family: arial,sans-serif;">
	Send my <select id="emailOption"><option value="0">watchlist</option><option value="1">portfolio</option></select> via e-mail&nbsp;&nbsp;<input type="button" value="Go" onclick="sendEMail();"></input><br>
	<span>Uses the default e-mail client on your computer.</span>
	</div>
	
	<hr id="emailHorLine" style="display:none;width:99%"/>

	<div class="muted text-center"><small>(Data and Charts provided by Yahoo! Finance)</small></div>
	
	<!-- Settings Modal -->
	<div id="settingsModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="settingsModalLabel" aria-hidden="true">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
			<h3 id="settingsModalLabel">Settings</h3>
		</div>
		<div class="modal-body">
			<form class="form-horizontal" onsubmit="return false;">
			<!--  
			  <div class="control-group">
			    <label class="control-label" for="inputTitle">Title</label>
			    <div class="controls">
			      <input type="text" id="inputTitle" placeholder="Uday's Quick Stock Watch">
			    </div>
			  </div>
			  -->
			  <div id="userMessage"></div>
			  <div class="control-group">
			    <label class="control-label" for="inputNewStock">Add new stock</label>
			    <div class="controls" id="inputNewStock">
			      <input type="text" class="input-medium" placeholder="Enter Symbol(s)" id="ticker" ><button type="submit" class="btn" id="tickeraddbtn" style="margin-left:5px">Add</button>
			    </div>
			  </div>
			  <div class="control-group">
			    <label class="control-label" for="inputHighlighting">Highlighting</label>
			    <div class="controls" id="inputHighlighting">
			      <select>
					  <option value="0">Off</option>
					  <option value="1">On</option>
					</select>
			    </div>
			  </div>
			  <div class="control-group">
			    <label class="control-label" for="inputRefreshRate">Refresh Rate</label>
			    <div class="controls" id="inputRefreshRate">
			      <select>
					  <option value="-1">No Refresh</option>
					  <option value="30">30 seconds</option>
					  <option value="60">1 minute</option>
					  <option value="300">5 minutes</option>
					</select>
			    </div>
			  </div>
			  <div class="control-group">
			    <label class="control-label" for="inputShowCharts">Show Charts</label>
			    <div class="controls" id="inputShowCharts">
			      <select>
					  	<option value="0">None</option>
						<option value="1">1 day</option>
						<option value="5">5 day</option>
						<option value="90">3 month</option>
						<option value="180">6 month</option>
						<option value="365">1 year</option>
					</select>
			    </div>
			  </div>
			  <div class="control-group">
			    <label class="control-label" for="inputShowStockName">Show Stock Name</label>
			    <div class="controls" id="inputShowStockName">
			      <select>
					  <option value="1">Yes</option>
					  <option value="0">No</option>
					</select>
			    </div>
			  </div>
			</form>
		</div>
		<div class="modal-footer">
			<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
			<button class="btn btn-primary" data-dismiss="modal" id="settingssavebtn">Save changes</button>
		</div>
	</div>
	
	<!-- Details Modal -->
	<div id="detailsModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel" aria-hidden="true">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
			<h3 id="detailsModalLabel">More Details on <span class="detailsmodalsymbol"></h3>
		</div>
		<div class="modal-body">
			<table class="table table-condensed table-striped">
				<tbody>
					<tr>
						<td>Symbol</td>
						<td><span class="detailsmodalsymbol"></span></td>
					</tr>
					<tr>
						<td>Name</td>
						<td><span class="detailsmodalname"></span></td>
					</tr>
					<tr>
						<td>Open</td>
						<td><span class="detailsmodalopen"></span></td>
					</tr>
					<tr>
						<td>PreviousClose</td>
						<td><span class="detailsmodalprevclose"></span></td>
					</tr>
					<tr>
						<td>Volume</td>
						<td><span class="detailsmodalvolume"></span></td>
					</tr>
					<tr>
						<td>Days Range</td>
						<td><span class="detailsmodaldaysrange"></span></td>
					</tr>
					<tr>
						<td>52-week Range</td>
						<td><span class="detailsmodalyearrange"></span></td>
					</tr>
					<tr>
						<td>Last Trade</td>
						<td><span class="detailsmodallasttrade"></span></td>
					</tr>
					<tr>
						<td>Exchange</td>
						<td><span class="detailsmodalexchange"></span></td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class="modal-footer">
			<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
		</div>
	</div>
	
	<!-- Delete Modal -->
	<div id="deleteModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
			<h3 id="deleteModalLabel">Delete from Watchlist</h3>
		</div>
		<div class="modal-body">
			<input type="hidden" id="deletekey" value=""/>
			Are you sure you want to delete <strong><span id="deletemodalname"></span></strong> from your watchlist? Please note that it will be removed from your portfolio as well.
		</div>
		<div class="modal-footer">
			<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
			<button class="btn btn-danger" data-dismiss="modal" id="deletesavebtn">Delete</button>
		</div>
	</div>
	
	<script src="http://code.jquery.com/jquery.js"></script>
	<script src="bootstrap/js/jquery.cookie.js"></script>
	<script src="bootstrap/js/bootstrap.min.js"></script>
	<script src="bootstrap/js/json2.js"></script>
	<script src="bootstrap/js/storage.js"></script>
	<script type="text/javascript" src="apigee.min.js"></script>
	
	<script type="text/javascript">
	
	var userId = null;
	var userPrefs = null;
	var debugBuf = []; 
	
	if (!window.console) {
		window.console = { log : function(s) { } };
	}
	
	function debugLog(str) {
		if(debugBuf.join(",").length<1000) {
			debugBuf.push(str);
		}
	}
	
	function userBrowser() {
	    var ua = navigator.userAgent, tem, 
	    M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
	    if(/trident/i.test(M[1])){
	        tem=  /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
	        return 'IE '+(tem[1] || '');
	    }
	    M = M[2]? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?'];
	    if((tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
	    return M[0];
	}
	
    var searchkey = self.location.search;
	if(searchkey!='') {
		searchkey = searchkey.substring(1);
		var pairs = searchkey.split("=");
		if(pairs[0]=="subscriptionid") {
			userId = pairs[1];
			userId = userId.replace("@","");
			if(userId=="token")
				userId = null;
		}
	}
	debugLog('1');
	debugLog(userId);
	
	//Redirect user to the new Github URL
	var url = self.location.href;
	url = url.replace('http://udaysasi-gadgets.googlecode.com/svn/trunk', 'http://udaysasigadgets.github.io');
	self.location.href=url;
	
	var client = new Usergrid.Client({
        orgName:'perfectpluto',
        appName:'sandbox'
    });
	debugLog('client');
	
    function getUserPrefs(callback) {
    	var prefTimeout = window.setTimeout(callback, 10000);
    	var opts = {
        	'type':'ighqswprefs',
        	'name':userId,
        	getOnExist:true,
        	'gadget':'qsw'
        };
       	client.createEntity(opts, function(err, pref) {
        	if(err) {
        		debugLog('createEntity cloud err');
        		console.log("Error creating preferences object");
        		/*Temporary Fix for IE users*/
        		userId = null;
        		/*
        		try {
    				var p = window.localStorage;
    				localStore.setItem = function(i,v) {
    					console.log("setting to localStorage : "+i+"="+v);
    					localStorage.setItem(i,v);
    				}
    				localStore.getItem = function(i) {
    					console.log("reading from localStorage : "+i);
    					return localStorage.getItem(i);
    				}
    				debugLog('createEntity cloud err => localStorage');
    			} catch(e) {
    			*/
    				console.log("seems to be inside an iframe, Using cookie instead..");
    				$.cookie("utest","Luigi", { expires: 365 });
    				console.log("Value read from cookie : "+$.cookie("utest"));
    				if($.cookie("utest")=="Luigi") {
    					console.log("cookies are enabled..");
    					debugLog('createEntity cookieenabled');
    				} else {
    					console.log("cookies are not enabled.. Notify the user..");
    					var userBrowserVersion = userBrowser();
    					$("#message").html("<small>Please <a href='http://www.google.com/search?q=enable+third+party+cookies+"+userBrowserVersion+"' target='new'>enable third party cookies</a> on your browser to view the gadget</small>").removeClass("hide");
    					debugLog('createEntity cookiedisabled');
    				}
    				localStore.setItem = function(i,v) {
    					console.log("setting to cookie : "+i+"="+v);
    					$.cookie(i, v, { expires: 365 });
    				}
    				localStore.getItem = function(i) {
    					console.log("reading from cookie : "+i);
    					return $.cookie(i);
    				}
    				debugLog('createEntity cloud err => cookie');
    			/*	
    			}
    			*/
    			//Inform the user
    			$("#message").removeClass("hide");
    			debugLog('createEntity callback');
    			callback();
    			/*Temporary Fix for IE users*/
        	} else {
        		debugLog('createEntity cloud');
        		console.log("Preferences object : "+pref.get('uuid'));
        		userPrefs = pref;
        		window.clearTimeout(prefTimeout);
    	        console.log("Cleared the timeout call..")
    	        debugLog('createEntity callback');
    	        callback();
        	}
        });
    }
	
	var autocomplete = null;
	var localStore = {
		setItem : null,
		getItem : null
	};
	
	if(userId!=null) {
		localStore.setItem = function(i,v) {
			if(userId=='token')
				return;
			console.log("setting to cloud : "+i+"="+v);
			userPrefs.set(i,v);
			userPrefs.save(function(err) {
				if(err) {
					console.log("Prefs not saved in the cloud - "+err);
					debugLog("ClS-Error");
				} else {
					debugLog("ClS"+i);
				}
			});
		}
		localStore.getItem = function(i) {
			console.log("reading from cloud : "+i);
			return userPrefs.get(i);
		}
		debugLog('cloud');
	} else {
		/*
		try {
			var p = window.localStorage;
			localStore.setItem = function(i,v) {
				console.log("setting to localStorage : "+i+"="+v);
				localStorage.setItem(i,v);
			}
			localStore.getItem = function(i) {
				console.log("reading from localStorage : "+i);
				return localStorage.getItem(i);
			}
			debugLog('localStorage');
		} catch(e) {
		*/	
			console.log("seems to be inside an iframe, Using cookie instead..");
			$.cookie("utest","Luigi", { expires: 365 });
			console.log("Value read from cookie : "+$.cookie("utest"));
			if($.cookie("utest")=="Luigi") {
				console.log("cookies are enabled..");
			} else {
				console.log("cookies are not enabled.. Notify the user..");
				var userBrowserVersion = userBrowser();
				$("#message").html("<small>Please <a href='http://www.google.com/search?q=enable+third+party+cookies+"+userBrowserVersion+"' target='new'>enable third party cookies</a> on your browser to view the gadget</small>").removeClass("hide");
			}
			localStore.setItem = function(i,v) {
				console.log("setting to cookie : "+i+"="+v);
				$.cookie(i, v, { expires: 365 });
			}
			localStore.getItem = function(i) {
				console.log("reading from cookie : "+i);
				return $.cookie(i);
			}
			debugLog('cookie');
		/*	
		}
		*/
	}
	
	function gel(id) {
		return $('#'+id);	
	}
	
	var YAHOO = {
	        Finance: {
	            SymbolSuggest: {
	            	
					ssCallback : function(feed) {  	  
	    				if (feed == null || feed["ResultSet"]==null || feed["ResultSet"]["Result"]==null){ 
	    					gel("myContainer").html("Error retrieving data");
	    					return;
	    			  	}
	    			  	var html = "", numResults = 0;
	    				dataArray = feed["ResultSet"]["Result"];
	    				var queryStr = feed["ResultSet"]["Query"];
	    				if(dataArray && dataArray.length)
	    				{
	    				  numResults  = dataArray.length;
	    				}
	    				
                        //Filter out your own parameters. Populate them into an array, since this is what typeahead's source requires
                        var arr = [], i=numResults;
                        while(i--){
                            arr[i] = dataArray[i]['name']
                        }
                        autocomplete.data('typeahead').source = function(query, process) {
                        	suggests = [];
                            map = {};  
                         
                            $.each(dataArray, function (i, d) {
                                map[d.symbol+" -> "+d.name] = d;
                                suggests.push(d.symbol+" -> "+d.name);
                            });
                         
                            process(suggests);
                        };
                        autocomplete.data('typeahead').updater = function (item) {
                            selectedSymbol = map[item].symbol;
                            return selectedSymbol;
                        }
                        autocomplete.trigger('keyup');
                        autocomplete.data('active', false);
                        //console.log("Unlocked and Ready for next input");
	    			  }
	            }
	        }
	};
	
	function searchTicker()
	{ 
	  var inputVal = gel("ticker").val();
	  var commaIndex = inputVal.lastIndexOf(",");
	  var prevStr = inputVal.substring(0, commaIndex);
	  var queryStr = inputVal.substring(commaIndex+1);
	  queryStr = trim(queryStr);

		$.ajax({
              type: "GET",
              url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
              data: {query: escape(queryStr)},
              dataType: "jsonp",
              async : false,
              jsonp : "callback",
              jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback"
          });
	}
	
	function getSelectedStr(origStr, matchStr)
	{
		var rg = new RegExp("\\b"+matchStr, "ig");
		var finalStr = origStr.replace(rg, "<b>"+origStr.match(rg)+"</b>");
		return finalStr;
	}

	function trim(str) {
	    return str.replace(/^\s*|\s*$/g, "");
	}
	
	$(document).ready(function() {
		
		var showname, flashing, showchart, refreshrate, showNews, showStrength, strTickers, stockTickers;
		var baseURL = "http://download.finance.yahoo.com/d?s=";
		var sortcol = 'symbol';
		var cURL = "http://ichart.finance.yahoo.com/t?s=";
		var newDate = new Date().getTime();
		var reloadId = "0";
		var newsReloadId = "0";
		var newsURL = 'http://finance.yahoo.com/rss/headline?s=';
		var newsItemArray = new Array();
		var staticImgUrl = "http://udaysasi-gadgets.googlecode.com/svn/trunk/delete.gif";
		
		//Amazon ads
		//$("#ad"+Math.floor(Math.random()*10)).removeClass('hide');
		function initWidget() {
			showname = localStore.getItem("showname");
			if(showname==null)
				showname = "1";
			flashing = localStore.getItem("flashing");
			if(flashing==null)
				flashing = "0";
			showchart = localStore.getItem("showchart");
			if(showchart==null)
				showchart = "1";
			refreshrate = localStore.getItem("refreshrate");
			if(refreshrate==null)
				refreshrate = "30";
			showNews = localStore.getItem("shownews");
			if(showNews==null)
				showNews = "0";
			showStrength = localStore.getItem("showstrength");
			if(showStrength==null)
				showStrength = "0";
			strTickers = localStore.getItem("tickers");
			if(strTickers==null)
				strTickers = "GOOG,FB";
			strTickers = convertToNewFormat(strTickers);
			stockTickers = convertToArray2(strTickers);
			
			stockTickers = sortArray(stockTickers);
			
			if(refreshrate!=-1 && refreshrate<30) {
				refreshrate = 30;
				localStore.setItem("refreshrate", 30);
			}
			if (showchart == 5) {
			    cURL = "http://ichart.finance.yahoo.com/v?s=";
			}
			else if (showchart == 90) {
			    cURL = "http://ichart.finance.yahoo.com/z?t=3m&l=off&z=b&s=";
			}
			else if (showchart == 180) {
			    cURL = "http://ichart.finance.yahoo.com/z?t=6m&l=off&z=b&s=";
			}
			else if (showchart == 365) {
			    cURL = "http://ichart.finance.yahoo.com/z?t=1y&l=off&z=b&s=";
			}
			
			var title = localStore.getItem("title");
			if(title!='' && title!="Uday's Quick Stock Watch")
				title += ' - Quick Stock Watch';
			
		}
		
		function NewsItem(title, link, time){ this.title = title;this.link = link;this.time = time;}
		
		function getAlphaNumericName(txtString)
		{
			txtString = txtString.toLowerCase();
			txtString = txtString.replace(/[^a-zA-Z 0-9]+/g,"");
			return txtString;
		}

		function callNewsServer()
		{ 
			var symbolArray = getSymbolArray();
		    if (symbolArray.length == 0) {
		        return;
		    }
		    var symbol = "";
		    for (var h = 0; h < symbolArray.length - 1; h++) {
		        symbol += symbolArray[h] + ",";
		    }
		    symbol += symbolArray[h];

			customAjax("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url%3D'http%3A%2F%2Ffeeds.finance.yahoo.com%2Frss%2F2.0%2Fheadline%3Fs%3D"+encodeURIComponent(encodeURIComponent(symbol))+"%26format%3Djson'&format=json", processNewsResponse);
			   
		}
		function processNewsResponse(r)
		{
			try 
			{ 
				var itemList = r["item"];	
				newsItemArray = new Array(); 
				for (var i = 0; i < itemList.length ; i++)  
				{ 
					if(i>=4) 
						break; 
					var node = itemList[i]; 
					var title = node["title"], link=node["link"], pubDate = node["pubDate"], diff;
					var newdate = new Date(pubDate);
					var curdate = new Date(new Date().toGMTString());
					diff = (curdate-newdate)/1000;
					if(isNaN(diff))
						diff = '';
					else if(diff<60)
						diff = ' - '+diff+' sec ago';
					else if(diff<60*60)
						diff = ' - '+Math.floor(diff/60) + ' min ago';
					else if(diff<60*60*24)
						diff = ' - '+Math.floor((diff/3600))+' hr '+Math.floor((diff%3600)/60)+' min ago';
					else{
						var days = Math.floor((diff/86400));
						diff = ' - '+days+(days>1?' days ago':' day ago');
					}
					newsItemArray = newsItemArray.concat(new NewsItem(title, link, diff)); 
				} 
				displayNewsContent();	 
			}
			catch(e){ }   
			
			newsReloadId = setTimeout(callNewsServer, 300000);	
		}
		
		function displayNewsContent()
		{
			var header = ''; 
			var footer = ''; 
			var contentText = '';  
			if(newsItemArray.length==0) 
				contentText = 'No news available for stocks in your watchlist'; 
			for (i=0;i<newsItemArray.length;i++) 
				contentText+='<li><a href="'+newsItemArray[i].link+'" target="newsT"><font size="-1">'+newsItemArray[i].title+'</font></a><font size="-1" color="#AAAAAA">'+newsItemArray[i].time+'</font></li>'; 		
			
			gel('newsContent').html(header+contentText+footer);		
		}
		
		showNewsContent = function() {
			clearTimeout(newsReloadId);
			showNews = localStore.getItem("shownews");
			if(showNews==0)
			{
				gel('newsContent').html('Loading news on stocks in your watch list..');
				gel('newsContent').css('display', '');
				gel('newsHorLine').css('display', '');
				callNewsServer();
				showNews = 1;		
				localStore.setItem("shownews", 1);
			}
			else
			{
				gel('newsContent').css('display', 'none');		
				gel('newsContent').html('');		
				gel('newsHorLine').css('display', 'none');		
				showNews = 0;
				localStore.setItem("shownews", 0);
			}
		}
		showStrengthContent = function() {
			showStrength = localStore.getItem("showstrength");
			if(showStrength==0)
			{
				gel('strengthContent').css('display', '');
				gel('strHorLine').css('display', '');
				showStrength = 1;		
				localStore.setItem("showstrength", 1);
			}
			else
			{
				gel('strengthContent').css('display', 'none');		
				gel('strHorLine').css('display', 'none');		
				showStrength = 0;
				localStore.setItem("showstrength", 0);
			}
		}
		
		function convertToString(arr) {
		    var returnString = "";
		    for (var g = 0; g < arr.length; g++) {
		        returnString += arr[g].symbol + ",";
		    }
		    return returnString;
		}
		
		function convertToString2(arr) {
		    var returnString = "";
		    for (var g = 0; g < arr.length; g++) {
		        returnString += arr[g].symbol + "|" + arr[g].numshares + "|" + arr[g].buyprice + ",";
		    }
		    return returnString;	
		}
		
		function convertToArray(str) {
		    var returnArray = new Array();
		    str = str.replace(/ /g, ",");
		    var ticks = str.split(",");
		    ticks.sort();
		    for (var d = 0; d < ticks.length; d++) {
		        var curTicker = ticks[d];
		        curTicker = curTicker.toUpperCase();
		        if (curTicker == "") {
		            continue;
		        }
		        returnArray.push(new StockTicker(curTicker, "Loading..", "0", "0", "(0%)"));
		    }
		    return returnArray;
		}
		
		function convertToNewFormat(str) {
			if(str.indexOf("|")!=-1)
				return str;
		    var returnString = "";
		    str = str.replace(/ /g, ",");
		    var ticks = str.split(",");
		    ticks.sort();
		    for (var d = 0; d < ticks.length; d++) {
		        var curTicker = ticks[d];
		        curTicker = curTicker.toUpperCase();
		        if (curTicker == "") {
		            continue;
		        }
		        returnString += curTicker + "|0|0.00,";        
		    }
		    return returnString;		
		}
		
		function convertToArray2(str) {
		    var returnArray = new Array();
		    str = str.replace(/ /g, ",");
		    var ticks = str.split(",");
		    ticks.sort();
		    for (var d = 0; d < ticks.length; d++) {
		        var curTicker = ticks[d];
		        curTicker = curTicker.toUpperCase();
		        var curTickerData = curTicker.split("|");
		        if (curTickerData[0] == "") {
		            continue;
		        }
		        returnArray.push(new StockTicker(curTickerData[0], "Loading..", "0", "0", "(0%)", curTickerData[1], curTickerData[2]));
		    }
		    return returnArray;
		}
		
		function StockTicker(symbol, name, price, change, percent, numshares, buyprice) {
		    this.symbol = symbol;
		    this.name = name;
		    this.price = price;
		    this.change = change;
		    this.percent = percent;
		    this.numshares = numshares;
		    this.buyprice = buyprice;
		}
		function getSymbolArray() {
		    var symbolArray = new Array();
		    for (u = 0; u < stockTickers.length; u++) {
		        symbolArray = symbolArray.concat(stockTickers[u].symbol);
		    }
		    return symbolArray;
		}
		
		function callServer() {
			getDowData();
		    var symbolArray = getSymbolArray();
		    if (symbolArray.length == 0) {
		        return;
		    }
		    var symbol = "";
		    for (var h = 0; h < symbolArray.length - 1; h++) {
		        symbol += symbolArray[h] + ",";
		    }
		    symbol += symbolArray[h];
		    var newDate = new Date().getTime();

		    customAjax("http://query.yahooapis.com/v1/public/yql?q=select+*+from+csv+where+url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D"+encodeURIComponent(encodeURIComponent(symbol))+"%26f%3Dnsl1p2c1p'+and+columns%3D'name%2Csymbol%2CLastTradePriceOnly%2CPercentChange%2CChange%2CPreviousClose'&format=json", responseText);
		    
		    try {
		        clearTimeout(reloadId);
		    }
		    catch (e) {
		    }    
			if (refreshrate != -1) {
				reloadId = setTimeout(callServer, refreshrate * 1000);
		    }
		}
		
		function getDowData() {
			var curQuoteTicker = "^DJI";
            var pos = getPosition(curQuoteTicker);
            if(pos==-1)
            	return;  
			//customAjax("http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20google.igoogle.stock%20WHERE%20stock%3D%22.DJI%22&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env", dowResponseText);
            $.ajax({
			    type: 'GET',
			    //url: "http://finance.google.com/finance/info?client=ig&q=.DJI",
				url: "http://quote.cnbc.com/quote-html-webservice/quote.htm?symbols=.DJIA&output=jsonp",
				async: false,
			    jsonpCallback: 'dowCallback',
			    contentType: "application/json",
			    dataType: 'jsonp',
			    success: function(json) {
			       console.log(json);
			       dowCallback(json);
			    },
			    error: function(e) {
			       console.log("Error getting Dow data : "+e.message);
			    }
			});
		}
		
		/*
		function dowCallback(responseArr) {
			if(!(responseArr && responseArr.length>0))
				return;
			
			var curQuote = responseArr[0];
            var curQuoteTicker = curQuote["t"];
            curQuoteTicker = "^DJI";
            var pos = getPosition(curQuoteTicker);
            if(pos==-1)
            	return;
        	
            var symbol = getSymbol(pos);
            if (symbol == "") {
                return;
            }
            var nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
            var priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
            var changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
            var percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
            var tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
            
            var tickerSpan2 = gel(getAlphaNumericName(symbol) + "Span2");
            var gainlossSpan2 = gel(getAlphaNumericName(symbol) + "GainLossSpan2");            
            
            var row = gel(getAlphaNumericName(symbol) + "Row");
            var curQuoteName = "Dow Jones Industrial Average";
            //curQuoteName = getRefinedName(curQuoteName);
            if (symbol == curQuoteName) {
                curQuoteName = "Invalid symbol";
            }
            //curQuoteName = getInitCaps(curQuoteName);
            if(curQuoteName.length>18)
            	curQuoteName = curQuoteName.substring(0,18);
            nameSpan.html(curQuoteName);
            if (showname == 0) {
                tickerSpan.attr("title", curQuoteName);
                tickerSpan2.attr("title", curQuoteName);
            }
            setName(pos, curQuoteName);
            var curQuotePrice = removeBold(curQuote["l"]);
            curQuotePrice = removeImageTag(curQuotePrice);
            curQuotePrice = removeItalics(curQuotePrice);
            var curQuoteChange = removeBold(curQuote["c"]);
            curQuoteChange = removeItalics(curQuoteChange);
            try {
                curQuotePrice = parseFloat(curQuotePrice.replace(",",""));
                if (curQuotePrice > 1) {
                    curQuotePrice = roundNumber(curQuotePrice);
                    curQuotePrice = round2Decimals(curQuotePrice);
                }
            } catch (e) {
                curQuotePrice = "N/A";
            }
            var curQuotePercentChange ="";
            try {
            	curQuotePercentChange = curQuote["cp"];
            } catch (e) {
					 curQuotePercentChange = "N/A";
			}
            curQuotePercentChange = removeBold(curQuotePercentChange);
            curQuotePercentChange = removeItalics(curQuotePercentChange);
            curQuotePercentChange = trim(curQuotePercentChange);
            try {
                curQuotePercentChange = parseFloat(curQuotePercentChange.replace(",",""));
                if (curQuotePrice > 1) {
                    curQuotePercentChange = roundNumber(curQuotePercentChange);
                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
                }
            }
            catch (e) {
                curQuotePercentChange = "N/A";
            }
            priceSpan.html(curQuotePrice);
            
            var curQuoteOldPrice = getPrice(pos);
            if (curQuoteOldPrice != "N/A" && curQuotePrice != "N/A" && flashing == 1) {
                if (curQuoteOldPrice > curQuotePrice) {
                	priceSpan.css('color', '#990000');
                	nameSpan.css('color', '#990000');
                } else {
                    if (curQuoteOldPrice < curQuotePrice) {
                    	priceSpan.css('color', '#009900');
                    	nameSpan.css('color', '#009900');
                    } else {
                    	priceSpan.css('color', '#000000')
                    	nameSpan.css('color', '#000000')
                    }
                }
            }
            setTimeout("javascript:restoreColor('" + symbol + "');", 200);
            setPrice(pos, curQuotePrice);
            if (isNaN(curQuoteChange)) {
                curQuoteChange = "N/A";
            } else {
            	try {
				    curQuoteChange = parseFloat(curQuoteChange.replace(",",""));
				    if (curQuotePrice > 1 || curQuoteChange==0) {
				        curQuoteChange = roundNumber(curQuoteChange);
				        curQuoteChange = round2Decimals(curQuoteChange);
				    } else {
				        curQuoteChange = Math.round(curQuoteChange * Math.pow(10, 3)) / Math.pow(10, 3);
				    }
            	} catch (e) {
                    curQuoteChange = "N/A";
            	}
            }
            setChange(pos, curQuoteChange);
            if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
                curQuoteChange = "+" + curQuoteChange;
            }
            changeSpan.html(curQuoteChange);
            if (isNaN(curQuotePercentChange)) {
                curQuotePercentChange = "N/A";
            } else {
                curQuotePercentChange = roundNumber(curQuotePercentChange);
                curQuotePercentChange = round2Decimals(curQuotePercentChange);
                if (curQuotePercentChange >= 0) {
                    curQuotePercentChange = "+" + curQuotePercentChange;
                }
            }
            
//            if (curQuotePercentChange < -3) {
//                n59c++;
//            } else {
//                if (curQuotePercentChange < -1) {
//                    n25c++;
//                } else {
//                    if (curQuotePercentChange < 0) {
//                        n02c++;
//                    } else {
//                        if (curQuotePercentChange > 3) {
//                            p59c++;
//                        } else {
//                            if (curQuotePercentChange > 1) {
//                                p25c++;
//                            } else {
//                                p02c++;
//                            }
//                        }
//                    }
//                }
//            }
            
            setPercentChange(pos, curQuotePercentChange);
            percentSpan.html("(" + curQuotePercentChange + "%)");
            if (parseFloat(curQuotePercentChange.replace(",","")) < 0 || parseFloat(curQuoteChange.replace(",","")) < 0) {
                changeSpan.css('color', '#990000');
                percentSpan.css('color', '#990000');
            } else if (parseFloat(curQuotePercentChange.replace(",","")) > 0 || parseFloat(curQuoteChange.replace(",","")) > 0) {
                changeSpan.css('color', '#009900');
                percentSpan.css('color', '#009900');
            } else {
                changeSpan.css('color', '#666666');
                percentSpan.css('color', '#666666');
            }
		}
		*/
		
		function dowCallback(responseData) {
			if(!(responseData && responseData["QuickQuoteResult"] && responseData["QuickQuoteResult"]["QuickQuote"]))
				return;
			var curQuote = responseData["QuickQuoteResult"]["QuickQuote"];
            
            var curQuoteTicker = curQuote["shortName"];
            curQuoteTicker = "^DJI";
            var pos = getPosition(curQuoteTicker);
            if(pos==-1)
            	return;
        	
            var symbol = getSymbol(pos);
            if (symbol == "") {
                return;
            }
            var nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
            var priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
            var changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
            var percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
            var tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
            
            var tickerSpan2 = gel(getAlphaNumericName(symbol) + "Span2");
            var gainlossSpan2 = gel(getAlphaNumericName(symbol) + "GainLossSpan2");            
            
            var row = gel(getAlphaNumericName(symbol) + "Row");
            var curQuoteName = "Dow Jones Industrial Average";
            //curQuoteName = getRefinedName(curQuoteName);
            if (symbol == curQuoteName) {
                curQuoteName = "Invalid symbol";
            }
            //curQuoteName = getInitCaps(curQuoteName);
            if(curQuoteName.length>18)
            	curQuoteName = curQuoteName.substring(0,18);
            nameSpan.html(curQuoteName);
            if (showname == 0) {
                tickerSpan.attr("title", curQuoteName);
                tickerSpan2.attr("title", curQuoteName);
            }
            setName(pos, curQuoteName);
            var curQuotePrice = removeBold(curQuote["last"]);
            curQuotePrice = removeImageTag(curQuotePrice);
            curQuotePrice = removeItalics(curQuotePrice);
            var curQuoteChange = removeBold(curQuote["change"]);
            curQuoteChange = removeItalics(curQuoteChange);
            try {
                curQuotePrice = parseFloat(curQuotePrice.replace(",",""));
                if (curQuotePrice > 1) {
                    curQuotePrice = roundNumber(curQuotePrice);
                    curQuotePrice = round2Decimals(curQuotePrice);
                }
            } catch (e) {
                curQuotePrice = "N/A";
            }
            var curQuotePercentChange ="";
            try {
            	curQuotePercentChange = curQuote["change_pct"];
            } catch (e) {
					 curQuotePercentChange = "N/A";
			}
            curQuotePercentChange = removeBold(curQuotePercentChange);
            curQuotePercentChange = removeItalics(curQuotePercentChange);
            curQuotePercentChange = trim(curQuotePercentChange);
            try {
                curQuotePercentChange = parseFloat(curQuotePercentChange.replace(",",""));
                if (curQuotePrice > 1) {
                    curQuotePercentChange = roundNumber(curQuotePercentChange);
                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
                }
            }
            catch (e) {
                curQuotePercentChange = "N/A";
            }
            priceSpan.html(curQuotePrice);
            
            var curQuoteOldPrice = getPrice(pos);
            if (curQuoteOldPrice != "N/A" && curQuotePrice != "N/A" && flashing == 1) {
                if (curQuoteOldPrice > curQuotePrice) {
                	priceSpan.css('color', '#990000');
                	nameSpan.css('color', '#990000');
                } else {
                    if (curQuoteOldPrice < curQuotePrice) {
                    	priceSpan.css('color', '#009900');
                    	nameSpan.css('color', '#009900');
                    } else {
                    	priceSpan.css('color', '#000000')
                    	nameSpan.css('color', '#000000')
                    }
                }
            }
            setTimeout("javascript:restoreColor('" + symbol + "');", 200);
            setPrice(pos, curQuotePrice);
            if (isNaN(curQuoteChange)) {
                curQuoteChange = "N/A";
            } else {
            	try {
				    curQuoteChange = parseFloat(curQuoteChange.replace(",",""));
				    if (curQuotePrice > 1 || curQuoteChange==0) {
				        curQuoteChange = roundNumber(curQuoteChange);
				        curQuoteChange = round2Decimals(curQuoteChange);
				    } else {
				        curQuoteChange = Math.round(curQuoteChange * Math.pow(10, 3)) / Math.pow(10, 3);
				    }
            	} catch (e) {
                    curQuoteChange = "N/A";
            	}
            }
            setChange(pos, curQuoteChange);
            if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
                curQuoteChange = "+" + curQuoteChange;
            }
            changeSpan.html(curQuoteChange);
            if (isNaN(curQuotePercentChange)) {
                curQuotePercentChange = "N/A";
            } else {
                curQuotePercentChange = roundNumber(curQuotePercentChange);
                curQuotePercentChange = round2Decimals(curQuotePercentChange);
                if (curQuotePercentChange >= 0) {
                    curQuotePercentChange = "+" + curQuotePercentChange;
                }
            }
            /*
            if (curQuotePercentChange < -3) {
                n59c++;
            } else {
                if (curQuotePercentChange < -1) {
                    n25c++;
                } else {
                    if (curQuotePercentChange < 0) {
                        n02c++;
                    } else {
                        if (curQuotePercentChange > 3) {
                            p59c++;
                        } else {
                            if (curQuotePercentChange > 1) {
                                p25c++;
                            } else {
                                p02c++;
                            }
                        }
                    }
                }
            }
            */
            setPercentChange(pos, curQuotePercentChange);
            percentSpan.html("(" + curQuotePercentChange + "%)");
            if (parseFloat(curQuotePercentChange.replace(",","")) < 0 || parseFloat(curQuoteChange.replace(",","")) < 0) {
                changeSpan.css('color', '#990000');
                percentSpan.css('color', '#990000');
            } else if (parseFloat(curQuotePercentChange.replace(",","")) > 0 || parseFloat(curQuoteChange.replace(",","")) > 0) {
                changeSpan.css('color', '#009900');
                percentSpan.css('color', '#009900');
            } else {
                changeSpan.css('color', '#666666');
                percentSpan.css('color', '#666666');
            }
		}
		
		function dowResponseText(responseString) {
			if(!(responseString && responseString.xml_api_reply && responseString.xml_api_reply.finance))
				return;
			
			var curQuote = responseString.xml_api_reply.finance;
			
			var curQuoteTicker = curQuote["symbol"]["data"];
			curQuoteTicker = "^DJI";
            var pos = getPosition(curQuoteTicker);
            if(pos==-1)
            	return;
        	
            var symbol = getSymbol(pos);
            if (symbol == "") {
                return;
            }
            var nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
            var priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
            var changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
            var percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
            var tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
            
            var tickerSpan2 = gel(getAlphaNumericName(symbol) + "Span2");
            var gainlossSpan2 = gel(getAlphaNumericName(symbol) + "GainLossSpan2");            
            
            var row = gel(getAlphaNumericName(symbol) + "Row");
            var curQuoteName = curQuote["company"]["data"]
            //curQuoteName = getRefinedName(curQuoteName);
            if (symbol == curQuoteName) {
                curQuoteName = "Invalid symbol";
            }
            //curQuoteName = getInitCaps(curQuoteName);
            if(curQuoteName.length>18)
            	curQuoteName = curQuoteName.substring(0,18);
            nameSpan.html(curQuoteName);
            if (showname == 0) {
                tickerSpan.attr("title", curQuoteName);
                tickerSpan2.attr("title", curQuoteName);
            }
            setName(pos, curQuoteName);
            var curQuotePrice = removeBold(curQuote["last"]["data"]);
            curQuotePrice = removeImageTag(curQuotePrice);
            curQuotePrice = removeItalics(curQuotePrice);
            var curQuoteChange = removeBold(curQuote["change"]["data"]);
            curQuoteChange = removeItalics(curQuoteChange);
            try {
                curQuotePrice = parseFloat(curQuotePrice);
                if (curQuotePrice > 1) {
                    curQuotePrice = roundNumber(curQuotePrice);
                    curQuotePrice = round2Decimals(curQuotePrice);
                }
            } catch (e) {
                curQuotePrice = "N/A";
            }
            var curQuotePercentChange ="";
            try {
            	curQuotePercentChange = curQuote["perc_change"]["data"];
            } catch (e) {
					 curQuotePercentChange = "N/A";
			}
            curQuotePercentChange = removeBold(curQuotePercentChange);
            curQuotePercentChange = removeItalics(curQuotePercentChange);
            curQuotePercentChange = trim(curQuotePercentChange);
            try {
                curQuotePercentChange = parseFloat(curQuotePercentChange);
                if (curQuotePrice > 1) {
                    curQuotePercentChange = roundNumber(curQuotePercentChange);
                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
                }
            }
            catch (e) {
                curQuotePercentChange = "N/A";
            }
            priceSpan.html(curQuotePrice);
            
            var curQuoteOldPrice = getPrice(pos);
            if (curQuoteOldPrice != "N/A" && curQuotePrice != "N/A" && flashing == 1) {
                if (curQuoteOldPrice > curQuotePrice) {
                	priceSpan.css('color', '#990000');
                	nameSpan.css('color', '#990000');
                } else {
                    if (curQuoteOldPrice < curQuotePrice) {
                    	priceSpan.css('color', '#009900');
                    	nameSpan.css('color', '#009900');
                    } else {
                    	priceSpan.css('color', '#000000')
                    	nameSpan.css('color', '#000000')
                    }
                }
            }
            setTimeout("javascript:restoreColor('" + symbol + "');", 200);
            setPrice(pos, curQuotePrice);
            if (isNaN(curQuoteChange)) {
                curQuoteChange = "N/A";
            } else {
            	try {
				    curQuoteChange = parseFloat(curQuoteChange);
				    if (curQuotePrice > 1 || curQuoteChange==0) {
				        curQuoteChange = roundNumber(curQuoteChange);
				        curQuoteChange = round2Decimals(curQuoteChange);
				    } else {
				        curQuoteChange = Math.round(curQuoteChange * Math.pow(10, 3)) / Math.pow(10, 3);
				    }
            	} catch (e) {
                    curQuoteChange = "N/A";
            	}
            }
            setChange(pos, curQuoteChange);
            if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
                curQuoteChange = "+" + curQuoteChange;
            }
            changeSpan.html(curQuoteChange);
            if (isNaN(curQuotePercentChange)) {
                curQuotePercentChange = "N/A";
            } else {
                curQuotePercentChange = roundNumber(curQuotePercentChange);
                curQuotePercentChange = round2Decimals(curQuotePercentChange);
                if (curQuotePercentChange >= 0) {
                    curQuotePercentChange = "+" + curQuotePercentChange;
                }
            }
            /*
            if (curQuotePercentChange < -3) {
                n59c++;
            } else {
                if (curQuotePercentChange < -1) {
                    n25c++;
                } else {
                    if (curQuotePercentChange < 0) {
                        n02c++;
                    } else {
                        if (curQuotePercentChange > 3) {
                            p59c++;
                        } else {
                            if (curQuotePercentChange > 1) {
                                p25c++;
                            } else {
                                p02c++;
                            }
                        }
                    }
                }
            }
            */
            setPercentChange(pos, curQuotePercentChange);
            percentSpan.html("(" + curQuotePercentChange + "%)");
            if (parseFloat(curQuotePercentChange) < 0 || parseFloat(curQuoteChange) < 0) {
                changeSpan.css('color', '#990000');
                percentSpan.css('color', '#990000');
            } else if (parseFloat(curQuotePercentChange) > 0 || parseFloat(curQuoteChange) > 0) {
                changeSpan.css('color', '#009900');
                percentSpan.css('color', '#009900');
            } else {
                changeSpan.css('color', '#666666');
                percentSpan.css('color', '#666666');
            }
		}
		
		function customAjax(myurl, callback) {
			$.ajax({
		        type: "GET",
		        url: myurl,
		        dataType: "json",
		        success: function(data) {
					callback(data.query.results);
		        }
		    });
		}
		
		function fixCommas(str) {
		    var x = 0;
		    while (str.indexOf("\"", x) >= 0) {
		        var y = str.indexOf("\"", x);
		        var z = str.indexOf("\"", y + 1);
		        var w = str.indexOf(",", y);
		        if (w > y && w < z) {
		            str = str.substring(0, w) + "." + str.substring(w + 1);
		        }
		        x = z + 1;
		    }
		    return str;
		}
		function responseText(responseString) {
		    var result = responseString.row;
		    try {
		    	var quotes = new Array();
		    	quotes.push(result);
		    	if($.isArray(result)) {
		    		quotes = result;
		    	}
		        var n59p = 0, n25p = 0, n02p = 0, p25p = 0, p02p = 0, p59p = 0;
		        var n59c = 0, n25c = 0, n02c = 0, p25c = 0, p02c = 0, p59c = 0;
		        var totalGainLoss = 0, portfolioValue = 0, todayTotalGainLoss = 0;
		        var totalGainLossSpan2 = gel("TotalGainLossSpan2");
		        var portfolioValueSpan2 = gel("PortfolioValueSpan2");
		        var todayTotalGainLossSpan2 = gel("TodayTotalGainLossSpan2");
		        
		        for (var c = 0; c < quotes.length; c++) {
		        
			    	var curQuote = quotes[c];
		            //var curQuoteDetail = fixCommas(curQuote).split(",");
		            var curQuoteTicker = curQuote["symbol"];
		            //curQuoteTicker = getRefinedSymbol(curQuoteTicker);
		            var pos = getPosition(curQuoteTicker);
		            if(pos==-1 || curQuoteTicker=='^DJI') {
		            	continue;
		            }
		        	
		            var symbol = getSymbol(pos);
		            if (symbol == "") {
		                continue;
		            }
		            var nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
		            var priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
		            var changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
		            var percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
		            var tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
		            
		            var tickerSpan2 = gel(getAlphaNumericName(symbol) + "Span2");
		            var todayGainlossSpan2 = gel(getAlphaNumericName(symbol) + "TodayGainLossSpan2");
		            var gainlossSpan2 = gel(getAlphaNumericName(symbol) + "GainLossSpan2");            
		            
		            var row = gel(getAlphaNumericName(symbol) + "Row");
		            var curQuoteName = curQuote["name"]
		            //curQuoteName = getRefinedName(curQuoteName);
		            if (symbol == curQuoteName) {
		                curQuoteName = "Invalid symbol";
		            }
		            //curQuoteName = getInitCaps(curQuoteName);
		            nameSpan.html(curQuoteName);
		            if (showname == 0) {
		                tickerSpan.attr("title", curQuoteName);
		                tickerSpan2.attr("title", curQuoteName);
		            }
		            setName(pos, curQuoteName);
		            var curQuotePrice = removeBold(curQuote["LastTradePriceOnly"]);
		            curQuotePrice = removeImageTag(curQuotePrice);
		            curQuotePrice = removeItalics(curQuotePrice);
		            var curQuoteChange = removeBold(curQuote["Change"]);
		            curQuoteChange = removeItalics(curQuoteChange);
		            try {
		                curQuotePrice = parseFloat(curQuotePrice);
		                if (curQuotePrice > 1) {
		                    curQuotePrice = roundNumber(curQuotePrice);
		                    curQuotePrice = round2Decimals(curQuotePrice);
		                }
		            } catch (e) {
		                curQuotePrice = "N/A";
		            }
		            var curQuotePercentChange ="";
		            try {
		            	curQuotePercentChange = curQuote["PercentChange"];
		            } catch (e) {
							 curQuotePercentChange = "N/A";
					}
		            curQuotePercentChange = removeBold(curQuotePercentChange);
		            curQuotePercentChange = removeItalics(curQuotePercentChange);
		            curQuotePercentChange = trim(curQuotePercentChange);
		            try {
		                curQuotePercentChange = parseFloat(curQuotePercentChange);
		                if (curQuotePrice > 1) {
		                    curQuotePercentChange = roundNumber(curQuotePercentChange);
		                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
		                }
		            }
		            catch (e) {
		                curQuotePercentChange = "N/A";
		            }
		            priceSpan.html(curQuotePrice);
		            
		            //Previous Close Price
		            var prevClosePrice = removeBold(curQuote["PreviousClose"]);
		            prevClosePrice = removeImageTag(prevClosePrice);
		            prevClosePrice = removeItalics(prevClosePrice);
		            try {
		            	prevClosePrice = parseFloat(prevClosePrice);
		                if (prevClosePrice > 1) {
		                	prevClosePrice = roundNumber(prevClosePrice);
		                	prevClosePrice = round2Decimals(prevClosePrice);
		                }
		            } catch (e) {
		            	prevClosePrice = "N/A";
		            }
		            
		            
		            var curQuoteOldPrice = getPrice(pos);
		            if (curQuoteOldPrice != "N/A" && curQuotePrice != "N/A" && flashing == 1) {
		                if (curQuoteOldPrice > curQuotePrice) {
		                	priceSpan.css('color', '#990000');
		                	nameSpan.css('color', '#990000');
		                } else {
		                    if (curQuoteOldPrice < curQuotePrice) {
		                    	priceSpan.css('color', '#009900');
		                    	nameSpan.css('color', '#009900');
		                    } else {
		                    	priceSpan.css('color', '#000000')
		                    	nameSpan.css('color', '#000000')
		                    }
		                }
		            }
		            setTimeout("javascript:restoreColor('" + symbol + "');", 200);
		            setPrice(pos, curQuotePrice);
		            if (isNaN(curQuoteChange)) {
		                curQuoteChange = "N/A";
		            } else {
		            	try {
						    curQuoteChange = parseFloat(curQuoteChange);
						    if (curQuotePrice > 1 || curQuoteChange==0) {
						        curQuoteChange = roundNumber(curQuoteChange);
						        curQuoteChange = round2Decimals(curQuoteChange);
						    } else {
						        curQuoteChange = Math.round(curQuoteChange * Math.pow(10, 3)) / Math.pow(10, 3);
						    }
		            	} catch (e) {
		                    curQuoteChange = "N/A";
		            	}
		            }
		            setChange(pos, curQuoteChange);
		            if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
		                curQuoteChange = "+" + curQuoteChange;
		            }
		            changeSpan.html(curQuoteChange);
		            if (isNaN(curQuotePercentChange)) {
		                curQuotePercentChange = "N/A";
		            } else {
		                curQuotePercentChange = roundNumber(curQuotePercentChange);
		                curQuotePercentChange = round2Decimals(curQuotePercentChange);
		                if (curQuotePercentChange >= 0) {
		                    curQuotePercentChange = "+" + curQuotePercentChange;
		                }
		            }
		            if (curQuotePercentChange < -3) {
		                n59c++;
		            } else {
		                if (curQuotePercentChange < -1) {
		                    n25c++;
		                } else {
		                    if (curQuotePercentChange < 0) {
		                        n02c++;
		                    } else {
		                        if (curQuotePercentChange > 3) {
		                            p59c++;
		                        } else {
		                            if (curQuotePercentChange > 1) {
		                                p25c++;
		                            } else {
		                                p02c++;
		                            }
		                        }
		                    }
		                }
		            }
		            setPercentChange(pos, curQuotePercentChange);
		            percentSpan.html("(" + curQuotePercentChange + "%)");
		            if (parseFloat(curQuotePercentChange) < 0 || parseFloat(curQuoteChange) < 0) {
		                changeSpan.css('color', '#990000');
		                percentSpan.css('color', '#990000');
		            } else if (parseFloat(curQuotePercentChange) > 0 || parseFloat(curQuoteChange) > 0) {
		                changeSpan.css('color', '#009900');
		                percentSpan.css('color', '#009900');
		            } else {
		                changeSpan.css('color', '#666666');
		                percentSpan.css('color', '#666666');
		            }
		            
					var gainLossValue = 0;
					var buyPrice = getBuyPrice(pos);
					var numShares = getNumShares(pos);
					if (isNaN(buyPrice))
						buyPrice = 0;
					if (isNaN(numShares))
						numShares = 0;	
					if (isNaN(curQuotePrice))
						curQuotePrice = 0;				
					gainLossValue = (curQuotePrice-buyPrice)*numShares;			
					gainLossValue = roundNumber(gainLossValue);
					gainLossValue = round2Decimals(gainLossValue);
		            gainlossSpan2.html(gainLossValue);
		            if(parseFloat(gainLossValue) < 0)
		            	gainlossSpan2.css('color', '#990000');
		            else if(parseFloat(gainLossValue) > 0)
		            	gainlossSpan2.css('color', '#009900');
					else            	
		            	gainlossSpan2.css('color', '#000000');
		            totalGainLoss = parseFloat(totalGainLoss) + parseFloat(gainLossValue);
		            portfolioValue = parseFloat(portfolioValue) + parseFloat(curQuotePrice*numShares);
		            
		            //Todays Gain/Loss
		            if (isNaN(prevClosePrice)) {
		            	
		            } else {
			            var todayGainLossValue = 0;
			            todayGainLossValue = (curQuotePrice-prevClosePrice)*numShares;			
			            todayGainLossValue = roundNumber(todayGainLossValue);
			            todayGainLossValue = round2Decimals(todayGainLossValue);
			            todayGainlossSpan2.html(todayGainLossValue);
			            if(parseFloat(todayGainLossValue) < 0)
			            	todayGainlossSpan2.css('color', '#990000');
			            else if(parseFloat(todayGainLossValue) > 0)
			            	todayGainlossSpan2.css('color', '#009900');
						else            	
							todayGainlossSpan2.css('color', '#000000');
			            todayTotalGainLoss = parseFloat(todayTotalGainLoss) + parseFloat(todayGainLossValue);
		            }
		            
		        }
		        todayTotalGainLoss = roundNumber(todayTotalGainLoss);
		        todayTotalGainLoss = round2Decimals(todayTotalGainLoss);
		        todayTotalGainLossSpan2.html(todayTotalGainLoss);
				if(parseFloat(todayTotalGainLoss) < 0)
					todayTotalGainLossSpan2.css('color', '#990000');
				else if(parseFloat(todayTotalGainLoss) > 0)
					todayTotalGainLossSpan2.css('color', '#009900');
				else            	
					todayTotalGainLossSpan2.css('color', '#000000');
				
		        totalGainLoss = roundNumber(totalGainLoss);
		        totalGainLoss = round2Decimals(totalGainLoss);
		        totalGainLossSpan2.html(totalGainLoss);
				if(parseFloat(totalGainLoss) < 0)
					totalGainLossSpan2.css('color', '#990000');
				else if(parseFloat(totalGainLoss) > 0)
					totalGainLossSpan2.css('color', '#009900');
				else            	
					totalGainLossSpan2.css('color', '#000000');        
		
		        portfolioValue = roundNumber(portfolioValue);
		        portfolioValue = round2Decimals(portfolioValue);
		        portfolioValueSpan2.html(portfolioValue);
		        
		        var total = n59c + n25c + n02c + p02c + p25c + p59c;
		        n59p = roundNumber(n59c * 100 / total);
		        n25p = roundNumber(n25c * 100 / total);
		        n02p = roundNumber(n02c * 100 / total);
		        p02p = roundNumber(p02c * 100 / total);
		        p25p = roundNumber(p25c * 100 / total);
		        p59p = roundNumber(p59c * 100 / total);
		        gel("n59").css('width', n59p + "%");
		        gel("n59").attr('title', n59c+" of "+total+" stocks in your watchlist down over 3%");
		        gel("n25").css('width', n25p + "%");
		        gel("n25").attr('title', n25c+" of "+total+" stocks in your watchlist down between 1% and 3%");
		        gel("n02").css('width', n02p + "%");
		        gel("n02").attr('title', n02c+" of "+total+" stocks in your watchlist down between 0% and 1%");
		        gel("p02").css('width', p02p + "%");
		        gel("p02").attr('title', p02c+" of "+total+" stocks in your watchlist up between 0% and 1%");
		        gel("p25").css('width', p25p + "%");
		        gel("p25").attr('title', p25c+" of "+total+" stocks in your watchlist up between 1% and 3%");
		        gel("p59").css('width', p59p + "%");
		        gel("p59").attr('title', p59c+" of "+total+" stocks in your watchlist up over 3%");
		    }
		    catch (e) {
		    }
		    
		}
		
		restoreColor = function(symbol) {
		    var priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
		    var nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
		    priceSpan.css('color', '#000000');
		    nameSpan.css('color', '#000000');
		}
		function getPrice(c) {
		    return stockTickers[c].price;
		}
		function setPrice(c, newPrice) {
		    stockTickers[c].price = newPrice;
		}
		function setPercentChange(c, newPercent) {
		    stockTickers[c].percent = newPercent;
		}
		function getSymbol(c) {
		    if (c < stockTickers.length) {
		        return stockTickers[c].symbol;
		    } else {
		        return "";
		    }
		}
		function getName(c) {
		    return stockTickers[c].name;
		}
		function setName(c, newName) {
		    stockTickers[c].name = newName;
		}
		function setChange(c, newChange) {
		    stockTickers[c].change = newChange;
		}
		function getNumShares(c) {
		    return stockTickers[c].numshares;
		}
		function getBuyPrice(c) {
		    return stockTickers[c].buyprice;
		}
		function setBuyPrice(c, newBuyPrice) {
		    stockTickers[c].buyprice = newBuyPrice;
		}
		function setNumShares(c, newNumShares) {
		    stockTickers[c].numshares = newNumShares;
		}
		
		function getRefinedSymbol(str) {
		    return str.substring(1, str.length - 1);
		}
		function getRefinedName(str) {
		    return str.substring(1, str.length - 1);
		}
		function addStockTicker() {
		    gel("myContainer").html(""); 
		    currentSelection=-1;
		
		    var newTickerString = gel("ticker").val();
		    if (newTickerString == "Enter Symbol(s)") {
		        return;
		    }

		    var userMessageTicker = newTickerString;
		    gel("ticker").attr("autocomplete", "off");
		    newTickerString = newTickerString.replace(/ /g, ",");
		    var newTickerArray = newTickerString.split(",");
		    var symbolArray = getSymbolArray();
		
			 // Check for URL too large error
			 if (symbolArray.length == 0) {
			 	 return;
			 }
			 var symbol = "";
			 for (var h = 0; h < symbolArray.length; h++) {
				 symbol += symbolArray[h] + ",";
			 }
		 	 for (var d = 0; d < newTickerArray.length; d++) {
				 symbol += newTickerArray[d] + ",";	
			 }	 
			 if(symbol.length>400) {
			 	 gel("ticker").val("");
			 	 
				 gel("logger").html("<span style='color:#ff5555'>You have reached the allowable limit on the number of stocks you can add to this gadget. Please delete a few symbols and try adding again..</span>");
				 gel("logger").css('display', '');  
				 
			 	 setTimeout("gel('logger').html('');gel('logger').css('display', 'none');", 5000);
			 	 return;
			 }
		    
			 for (var d = 0; d < newTickerArray.length; d++) {
		        var currentTicker = newTickerArray[d];
		        currentTicker = currentTicker.toUpperCase();
		        if (currentTicker == "") {
		            continue;
		        }
		        var symbolPresent = false;
		        for (var g = 0; g < stockTickers.length; g++) {
		            if (stockTickers[g].symbol == currentTicker) {
		                symbolPresent = true;
		            }
		        }
		        if (symbolPresent) {
		            continue;
		        }
		        stockTickers.push(new StockTicker(currentTicker, "Loading..", "0", "0", "0", "0", "0.00"));
			 }
			 localStore.setItem("tickers", convertToString2(stockTickers));
			 $("#settingsModal").modal('hide');
			 stockTickers = sortArray2(stockTickers, sortcol);
			 paintStockTicker();
			 gel("ticker").val("");
			 $("#userMessage").addClass("alert alert-success").html(userMessageTicker+" added to your watchlist").show();
			 setTimeout(function() {
				 $("#userMessage").hide();
			 }, 5000);
		}
		function paintStockTicker() {
			 if(showNews==1)
			 {
			 	 gel('newsContent').html('Loading news on stocks in your watch list..');
				 gel('newsContent').css('display', '');
				 gel('newsHorLine').css('display', '');
				 clearTimeout(newsReloadId);
				 callNewsServer();
			 }
			 if(showStrength==1)
			 {
			 	 gel('strengthContent').css('display', '');
				 gel('strHorLine').css('display', '');
			 }	 
			 	
		    var fsize, nameDisplay;
		    if (showname == 1) {
		        fsize = "8";
		        nameDisplay = "";
		    } else {
		        fsize = "9";
		        nameDisplay = "none";
		    }
		    
		    var header = "<table class=\"table table-condensed table-striped\" align=center style=\"border:0;  font-family: arial,sans-serif;\" width=\"100%\" id=\"contentTable\" cellspacing=0 cellpadding=0>";
			header+= "<tr>";
			header+="<td align=left>&nbsp;</td>";
			header+="<td align=left style=\"padding-right: 0.5em;\"><a title=\"Click to sort by symbol\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('symbol');\"><font size=\"-1\"><b>Sym</b></font></td>";
			header+="<td align=left style=\"display:" + nameDisplay + "\" ><a title=\"Click to sort by name\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('name');\"><font size=\"-1\"><b>Name</b></a></font></td>";
			header+="<td align=right style=\"padding-right: 0.5em;\"><a title=\"Click to sort by price\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('price');\"><font size=\"-1\"><b>Price</b></a></font></td>";
			header+="<td align=right style=\"padding-right: 0.5em;\"><a title=\"Click to sort by price change\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('change');\"><font size=\"-1\"><b>Chng</b></a></font></td>";
			header+="<td align=right><a title=\"Click to sort by percentage change\" href=\"javascript:void(0);\" onclick=\"javascript:sortByColumn('percent');\"><font size=\"-1\"><b>%Chng</b></a></font></td>";
			header+="</tr>";
		    
		    var footer = "</table>";
		    var contentText = "";
		    for (i = 0; i < stockTickers.length; i++) {
		    	contentText += "<tr id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "Row\" style=\"background:#ffffff;\" onMouseOver=\"highlightColor(this);showChart('" + stockTickers[i].symbol + "')\" onMouseOut=\"unhighlightColor(this);hideChart('" + stockTickers[i].symbol + "')\">";
		        contentText += "<td style=\"padding-right: 3px;\" width=\"5%\" align=\"center\" title=\"Delete " + stockTickers[i].symbol + "\"><img src=\""+staticImgUrl+"\" onClick=\"javascript:deleteStockTicker(" + i + ")\"/></td>";
		        contentText += "<td width=\"5%\" align=left style=\"padding-right: 0.5em;\"><font size=\"-1\"><span rel=\"popover\" id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "Span\"><a href=\"http://finance.yahoo.com/q?s=" + stockTickers[i].symbol + "\" target=\"blank\">" + stockTickers[i].symbol + "</a></span></font></td>";
		        contentText += "<td nowrap style=\"display:" + nameDisplay + "\" width=\"35%\" align=left onClick=\"callMoreData('" + stockTickers[i].symbol + "')\" ><font size=\"-1\"><span style=\"display:" + nameDisplay + "\" id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "NameSpan\">" + stockTickers[i].name + "</span></font></td>";
		        contentText += "<td width=\"20%\" style=\"padding-right: 0.5em;\" align=right onClick=\"callMoreData('" + stockTickers[i].symbol + "')\" ><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "PriceSpan\">" + stockTickers[i].price + "</span></font></td>";
		        contentText += "<td width=\"15%\" style=\"padding-right: 0.5em;\" align=right nowrap onClick=\"callMoreData('" + stockTickers[i].symbol + "')\" ><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "ChangeSpan\">" + stockTickers[i].change + "</span></font></td>";
		        contentText += "<td width=\"15%\" align=right nowrap onClick=\"callMoreData('" + stockTickers[i].symbol + "')\" ><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "PercentSpan\">" + stockTickers[i].percent + "</span></font></td>";
		        contentText += "</tr>";
		    }
		    gel("watchListContent").html(header + contentText + footer);
		    $("td[align='right']").css("text-align", "right");
		    paintPortfolio();
		    try {
		        clearTimeout(reloadId);
		    }
		    catch (e) {
		    }
		    callServer();    
		}
		
		function paintPortfolio() {
		    var fsize, nameDisplay;
		    if (showname == 1) {
		        fsize = "8";
		        nameDisplay = "";
		    } else {
		        fsize = "9";
		        nameDisplay = "none";
		    }	
		    var header = "<table class=\"table table-condensed table-striped\"  align=center style=\"border:0;  font-family: arial,sans-serif;\" width=\"100%\" cellspacing=0 cellpadding=0>";
			 header+= "<tr>";
			 header+="<td align=left><a href=\"javascript:void(0);\"><font size=\"-1\"><b>Sym</b></font></a></td>";
			 header+="<td align=right><font size=\"-1\"><a href=\"javascript:void(0);\"><b>Qty</b></a></font></td>";
			 header+="<td align=right><font size=\"-1\"><a href=\"javascript:void(0);\"><b>Buy Price</b></a></font></td>";
			 header+="<td align=right><font size=\"-1\"><a href=\"javascript:void(0);\"><b>Today's Change</b></a></font></td>";
			 header+="<td align=right><font size=\"-1\"><a href=\"javascript:void(0);\"><b>Total Gain/Loss</b></a></font></td>";
			 header+="</tr>";
		     
			var footer = "<tr><td align=\"right\" colspan=\"3\"><font size=\"-1\">Portfolio Value : <b><span id=\"PortfolioValueSpan2\">0.00</span></font></b></td> <td align=\"right\"><font size=\"-1\"><b><span id=\"TodayTotalGainLossSpan2\">0.00</span><b></font></td>	<td align=\"right\"><font size=\"-1\"><b><span id=\"TotalGainLossSpan2\">0.00</span><b></font></td></tr></table>";
			var contentText = "";
		
		    for (i = 0; i < stockTickers.length; i++) {
		        contentText += "<tr id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "PortfolioRow\" style=\"background:#ffffff;\" onMouseOver=\"highlightColor(this);\" onMouseOut=\"unhighlightColor(this);\">";
		        contentText += "<td width=\"15%\" align=left><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "Span2\"><a href=\"http://finance.yahoo.com/q?s=" + stockTickers[i].symbol + "\" target=\"blank\">" + stockTickers[i].symbol + "</a></span></font></td>";
		        contentText += "<td width=\"20%\" align=right nowrap onclick='javascript:makeEditable(\""+getAlphaNumericName(stockTickers[i].symbol)+"numshares\", "+i+");' ><font size=\"-1\"><span id=\"span" + getAlphaNumericName(stockTickers[i].symbol) + "numshares\" style=\"display:\" >" + stockTickers[i].numshares + "</span><input type=\"text\" class=\"input-small\" size=\"4\" style=\"text-align:right;display:none\" id=\"text"+getAlphaNumericName(stockTickers[i].symbol)+"numshares\" onblur='javascript:makeUnEditable(\""+getAlphaNumericName(stockTickers[i].symbol)+"numshares\", "+i+",\"numshares\");'></font></td>";
		        contentText += "<td width=\"20%\" align=right nowrap onclick='javascript:makeEditable(\""+getAlphaNumericName(stockTickers[i].symbol)+"buyprice\", "+i+");' ><font size=\"-1\"><span id=\"span" + getAlphaNumericName(stockTickers[i].symbol) + "buyprice\" style=\"display:\" >" + stockTickers[i].buyprice + "</span><input type=\"text\" class=\"input-small\" size=\"4\" style=\"text-align:right;display:none\" id=\"text"+getAlphaNumericName(stockTickers[i].symbol)+"buyprice\" onblur='javascript:makeUnEditable(\""+getAlphaNumericName(stockTickers[i].symbol)+"buyprice\", "+i+",\"buyprice\");'></font></td>";
		        contentText += "<td width=\"20%\" align=right nowrap><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "TodayGainLossSpan2\">0.00</span></font></td>";
		        contentText += "<td width=\"25%\" align=right nowrap><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "GainLossSpan2\">0.00</span></font></td>";
		        contentText += "</tr>";        
		    }
		    gel("portfolioContent").html(header + contentText + footer);
		    $("td[align='right']").css("text-align", "right");
		}
		deleteStockTicker = function(k) {
			loadDeleteModal(k);
		}
		loadDeleteModal = function(k) {
			var name = getName(k)+' ['+getSymbol(k)+']';
			$("#deletekey").val(k);
			$("#deletemodalname").html(name);
			$("#deleteModal").modal('show');	
		}
		confirmDeleteModal = function() {
			var k = $("#deletekey").val();
			stockTickers.splice(k, 1);
			localStore.setItem("tickers", convertToString2(stockTickers));
		    stockTickers = sortArray2(stockTickers, sortcol);
		    paintStockTicker();
		}
		
		function roundNumber(num) {
		    var rlength = 2;
		    var newnumber = Math.round(num * Math.pow(10, rlength)) / Math.pow(10, rlength);
		    return newnumber;
		}
		highlightColor = function (highlightRow) {
		    highlightRow.style.backgroundColor = '#EEEEFF';
		}
		unhighlightColor = function (highlightRow) {
			highlightRow.style.backgroundColor = '#FFFFFF';
		}
		showChart = function (sym) {
		    if (showchart == 0) {
		        return;
		    }
		    
		    var img = "<img src='" + cURL + sym + "'/>";
		    gel(getAlphaNumericName(sym) + "Span").popover({'title':'', 'content': img, 'trigger':'hover', 'html': true});
		}
		hideChart = function (sym) {
		    if (showchart == 0) {
		        return;
		    }
		   
		    gel("logger").html("");
		    gel("logger").css('display', 'none');
		}
		function getPosition(sym) {
			var pos = 0;
			var arr = stockTickers;
			for(var l = 0; l < arr.length; l++) {
				if(arr[l].symbol.toUpperCase()==sym.toUpperCase())
					return (l);
			}
			return -1;
		}
		
		function processMoreData(responseArr) {
			if(!(responseArr && responseArr.length>0))
				return;
			
			var curQuote = responseArr[0];
			
			var newObjForModal = { row : {
				"symbol" : "^DJI",
				"name" : "Dow Jones Industrial Average",
				"Open" : "Unavailable",
				"PreviousClose" : "Unavailable",
				"Volume" : "Unavailable",
				"DaysRange" : "Unavailable",
				"YearRange" : "Unavailable",
				"LastTradeTime" : curQuote["ltt"],
				"StockExchange" : curQuote["e"]
			} };
			showMoreData(newObjForModal);
		}
		
		function showMoreData(responseString) {
			var results = responseString.row;
			$(".detailsmodalsymbol").html(results["symbol"]);
			$(".detailsmodalname").html(results["name"]);
			$(".detailsmodalopen").html(results["Open"]);
			$(".detailsmodalprevclose").html(results["PreviousClose"]);
			$(".detailsmodalvolume").html(results["Volume"]);
			$(".detailsmodaldaysrange").html(results["DaysRange"]);
			$(".detailsmodalyearrange").html(results["YearRange"]);
			$(".detailsmodallasttrade").html(results["LastTradeTime"]);
			$(".detailsmodalexchange").html(results["StockExchange"]);
			
			$("#detailsModal").modal('show');
			return;
		}
		hideMoreDiv = function(sym) {
		    var chartDiv = gel(getAlphaNumericName(sym) + "chartDiv");
		    chartDiv.css('display', 'none');
		    chartDiv.html("");    
		    gel("logger").html("");
		    gel("logger").css('display', 'none');
		    
		}
		function hideAllMoreDivs(arr) {
		    for (var l = 0; l < arr.length; l++) {
		        hideMoreDiv(arr[l].symbol);
		    }    
		}
		
		function _IG_Callback(callbackFunction, parameters) {
		  var args = arguments;
		  return function() {
		    var combinedArgs = Array.prototype.slice.call(arguments);
		    callbackFunction.apply(null,
		      combinedArgs.concat(Array.prototype.slice.call(args,1)))
		  }
		}
		
		callMoreData = function(sym) {
			if(sym=="^DJI") {
				//customAjax("http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20google.igoogle.stock%20WHERE%20stock%3D%22.DJI%22&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env", processMoreData);
	            $.ajax({
				    type: 'GET',
				    url: "http://finance.google.com/finance/info?client=ig&q=.DJI",
				    async: false,
				    jsonpCallback: 'processMoreData',
				    contentType: "application/json",
				    dataType: 'jsonp',
				    success: function(json) {
				       console.log(json);
				       processMoreData(json);
				    },
				    error: function(e) {
				       console.log("Error getting Dow data : "+e.message);
				    }
				});
			} else {
		    	customAjax("http://query.yahooapis.com/v1/public/yql?q=select+*+from+csv+where+url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D"+encodeURIComponent(encodeURIComponent(sym))+"%26f%3Dnsopvmwt1x'+and+columns%3D'name%2Csymbol%2cOpen%2CPreviousClose%2CVolume%2CDaysRange%2CYearRange%2CLastTradeTime%2CStockExchange'&format=json", showMoreData);
			}
		}
		function formatData(str) {
		    str = str.replace("\n", "").replace("\r", "");
		    if (str.indexOf("\"") == -1) {
		        return str;
		    } else {
		        return str.substring(1, str.length - 1);
		    }
		}
		function round2Decimals(n) {
		    var stringNumber = "" + n;
		    if (stringNumber.indexOf(".") == -1) {
		        stringNumber += ".00";
		    } else {
		        if (stringNumber.substring(stringNumber.indexOf(".") + 1).length == 1) {
		            stringNumber += "0";
		        }
		    }
		    return stringNumber;
		}
		function sortArray(arr) {
		    if (arr.length == 0) {
		        return arr;
		    }
		    var newArray = new Array();
		    var stA = new Array();
		    for (var l = 0; l < arr.length; l++) {
		        stA.push(arr[l].symbol);
		    }
		    stA.sort();
		    for (var h = 0; h < stA.length; h++) {
		        for (var o = 0; o < arr.length; o++) {
		            if (stA[h] == arr[o].symbol) {
		                newArray.push(arr[o]);
		            }
		        }
		    }
		    return newArray;
		}
		
		function sortArray2(tickcopy, col) {
			sortcol = col;
		
			var exp = 'tickers[l].'+col;
		
			var tickers = new Array();
			var nA = new Array();
			var stA = new Array();	
			for(k=0;k<tickcopy.length;k++)
				tickers.push(tickcopy[k]);
		
			for (var l = 0; l < tickers.length; l++) {
				if(parseFloat(eval(exp)))
					stA.push(parseFloat(eval(exp)));
				else
					stA.push(eval(exp));
			}
			if(col=='price' || col=='change' || col=='percent')
			{
				try{
					stA.sort(sortNumber);
				}catch(e) {
					stA.sort();
				}
			}
			else
				stA.sort();
		
			for (var h = 0; h < stA.length; h++) {
				for (var l = 0; l < tickers.length; l++) {
					if(nA.contains(tickers[l]))
						continue;
			
					if(parseFloat(stA[h]))
					{
						if (parseFloat(stA[h]) == parseFloat(eval(exp))) {					
							nA.push(tickers[l]);
						}
					}
					else
					{
						if (stA[h] == eval(exp)) {
							nA.push(tickers[l]);
						}
					}
				}
			}
			tickers = nA;
		
			return tickers;
		
		}
		function sortNumber(a,b)
		{
			if(a-b)
				return a-b;
			else
				return true;
		}
		sortByColumn = function (col)
		{
			stockTickers = sortArray2(stockTickers, col);
			paintStockTicker();
		}
		
		function removeBold(str) {
		    var boldIndexStart = str.indexOf("<b>");
		    var boldIndexEnd = str.lastIndexOf("</b>");
		    if (boldIndexStart == -1) {
		        return str;
		    }
		    var curQuotePrice = str.substring(boldIndexStart + 3, boldIndexEnd);
		    return curQuotePrice;
		}
		function removeItalics(str) {
		    var italicIndexStart = str.indexOf("<i>");
		    var italicIndexEnd = str.lastIndexOf("</i>");
		    if (italicIndexStart == -1) {
		        return str;
		    }
		    var curQuotePrice = str.substring(italicIndexStart + 3, italicIndexEnd);
		    return curQuotePrice;
		}
		function removeImageTag(str) {
			var imgstart = str.indexOf("<img");
		    if (imgstart == -1) {
		        return str;
		    }	
		    var csis = str.indexOf(">", imgstart);
		    var curQuotePrice = str.substring(0,imgstart)+str.substring(csis + 1);
		    return curQuotePrice;
		}
		function dismissMessage(i) {
			localStore.setItem("promo" + i, 1);
		}
		function joinString(a, b) {
		    var onelen = a.length;
		    var twolen = (a.length + b.length > 20) ? (20 - a.length) : b.length;
		    if (twolen != b.length) {
		        b = b.substring(0, twolen) + "..";
		    }
		    var res = b + " (" + a + ")";
		    return res;
		}
		boxFocus = function(val) {
		    var newTickerString = gel("ticker").val();
		    if (val == 0) {
				gel("ticker").attr("autocomplete","off");    
		        if (newTickerString == "Enter Symbol(s)") {
		            gel("ticker").val("");
		            gel("ticker").css('color', '#000000');
		        }
		    } else {
		        if (newTickerString == "") {
		            gel("ticker").val("Enter Symbol(s)");
		            gel("ticker").css('color', '#AAAAAA');
		        }
		    }
		}
		function getInitCaps(nt) {
		    var sarr = nt.split(" ");
		    var r = "";
		    for (i = 0; i < sarr.length; i++) {
		        var s = sarr[i].toLowerCase();
		        for (j = 0; j < s.length; j++) {
		            if (j == 0) {
		                r += s.charAt(j).toUpperCase();
		            } else {
		                r += s.charAt(j);
		            }
		        }
		        r += " ";
		    }
		    r = r.substring(0, r.length - 1);
		    return r;
		}
		
		Array.prototype.contains = function(element)   {
			for (var i = 0; i < this.length; i++)
				if (this[i] == element)
					return true;
			return false;
		}
		
		var view = "watchlist";
		toggleView = function() {
			view = gel('view').html().toLowerCase();
			if(view=='portfolio')
			{
				showPortfolio();	
				gel('view').html('Watchlist');
				gel('profitChart').css('display', '');
			}
			else
			{
				showWatchlist();						
				gel('view').html('Portfolio');
				gel('profitChart').css('display', 'none');
				gel('chartContent').css('display', 'none');
				gel('chartHorLine').css('display', 'none');
			}	
			
		}
		
		function showPortfolio()
		{
			gel("portfolioContent").css('display', '');
			gel("watchListContent").css('display', 'none');	
			
		}
		
		function showWatchlist()
		{
			gel("portfolioContent").css('display', 'none');
			gel("watchListContent").css('display', '');	
			
		}
		
		makeEditable = function (objname, i)
		{
			var textObj = gel('text'+objname);
			var spanObj = gel('span'+objname);
		
			textObj.val(spanObj.html());
			spanObj.css('display', 'none');
			textObj.css('display', '');
			textObj.select();
		}
		
		makeUnEditable = function (objname, i, attr)
		{
			var textObj = gel('text'+objname);
			var spanObj = gel('span'+objname);
			if(textObj.val()=='')
				textObj.val(0);
		
			var val = textObj.val();
			if (!isNaN(val))
			{
				if(val>1||val<=0) {
					val = roundNumber(val);
					if(objname.indexOf('buyprice')!=-1)
						textObj.val(round2Decimals(val));
				}
				spanObj.html(textObj.val());
				textObj.css('display', 'none');
				spanObj.css('display', '');
		
				if(attr=='buyprice')
					setBuyPrice(i, spanObj.html());
				else if(attr=='numshares')
					setNumShares(i, spanObj.html());
				paintStockTicker();
				localStore.setItem("tickers", convertToString2(stockTickers));
			} 
		}
			
		showEmailContent = function() {
			if(gel('emailContent').css('display')=='none')
			{
			 gel('emailContent').css('display', '');
			 gel('emailHorLine').css('display', '');	 
			}
			else
			{
			 gel('emailContent').css('display', 'none');
			 gel('emailHorLine').css('display', 'none');	 	
			}
		}
		
		sendEMail = function() {
			if(stockTickers.length<1)
				return;
			var emailSection = gel('emailOption').val();
			var ticks = '';var j=0;
			if(emailSection=='0')
			{	
				for(j=0;j<stockTickers.length-1;j++)
				{
					ticks += stockTickers[j].symbol+', ';
				}
				ticks += stockTickers[j].symbol;
				var sub = 'My Watchlist on Quick Stock Watch';
				var body = 'Hi there, %0A%0AHere are the stocks in my watchlist on Quick Stock Watch : '+ticks+'%0A%0AThanks';
			}
			else
			{
				var tempArr = new Array();
				for(p=0;p<stockTickers.length;p++)
				{
					if(stockTickers[p].numshares!='0')
						tempArr.push(stockTickers[p]);
				}
				if(tempArr.length<1)
					return;				
				for(j=0;j<tempArr.length-1;j++)
				{
					ticks += 'Bought '+tempArr[j].numshares+' shares of '+tempArr[j].symbol+' at '+tempArr[j].buyprice+' - Gain/Loss: '+gel(tempArr[j].symbol+'GainLossSpan2').html()+'%0A';
				}
				ticks += 'Bought '+tempArr[j].numshares+' shares of '+tempArr[j].symbol+' at '+tempArr[j].buyprice+' - Gain/Loss: '+gel(tempArr[j].symbol+'GainLossSpan2').html();
				var sub = 'My Portfolio on Quick Stock Watch';
				var body = 'Hi there, %0A%0AHere is my portfolio on Quick Stock Watch : %0A%0A'+ticks+'%0A%0AThanks';
			}
			window.location='mailto:?subject='+sub+'&body='+body;	
		}
		
		var numResults = 0;
		var currentSelection = -1;
		addEntry = function (symbol)
		{
		  var inputTextObj = gel("ticker");
		  var addedString = "";
		  var inputVal = inputTextObj.val();
		  var commaIndex = inputVal.lastIndexOf(",");
		  
		  if(commaIndex!=-1)
		  {
		    var prevStr = inputVal.substring(0, commaIndex);
		    addedString += prevStr + ", "; 
		  }
		  inputTextObj.val(addedString+symbol+", ");   
		  gel("myContainer").html(""); 
		  currentSelection=-1;
		  if(inputTextObj.createTextRange) {
			  var txtRange = inputTextObj.createTextRange();
			  txtRange.moveStart("character", inputTextObj.val().length);
			  txtRange.moveEnd( "character", 0 );
			  txtRange.select();
		  }
		  else if(inputTextObj.selectionStart) {
		      inputTextObj.focus(); 
		      inputTextObj.setSelectionRange(inputTextObj.val().length, inputTextObj.val().length);  	
		  }
		}
		
		keyEnter = function(e)
		{
		  var key = (window.Event) ? e.which : e.keyCode;
		  switch(key) {
		    case 40: case 38: case 13:
		      return;
		  }
		  currentSelection = -1;
		  numResults = 0;
		  var inputVal = gel("ticker").val();
		  var commaIndex = inputVal.lastIndexOf(",");
		  var prevStr = inputVal.substring(0, commaIndex);
		  var queryStr = inputVal.substring(commaIndex+1);
		  queryStr = trim(queryStr);

			$.ajax({
	              type: "GET",
	              url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
	              data: {query: escape(queryStr)},
	              dataType: "jsonp",
	              async : false,
	              jsonp : "callback",
	              jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback"
	          });
		}
		
		keyPress = function (e) {
			var key = (window.Event) ? e.which : e.keyCode;
		    switch(key) {
		    	case 40: case 38:
		    		moveSelection(key);
		    		break;  
		    	case 13:
		    		makeSelection(key);
		    		break; 
		    }
		}
		
		function moveSelection(keyCode) {
			var dataTable = gel("dataTable");
			if(!dataTable)
			  return;
			switch(keyCode) {
		    	case 40:
		    		for(var p=0;p<dataTable.children().children().length;p++)
		    			unhighlightSuggest(dataTable.children().children().eq(p));
		    		currentSelection++;
		    		if(currentSelection>numResults-1)
		    			currentSelection = 0;
		    		highlightSuggest(dataTable.children().children().eq(currentSelection));
		    		break;
		    	case 38:
		    		for(var p=0;p<dataTable.children().children().length;p++)
		    			unhighlightSuggest(dataTable.children().children().eq(p));
		    		currentSelection--;
		    		if(currentSelection<0)
		    			currentSelection = numResults-1;
		    		highlightSuggest(dataTable.children().children().eq(currentSelection));
		    		break;
			}
		}
		
		function makeSelection(keyCode) {
			var dataTable = gel("dataTable"); 
			if(!dataTable || currentSelection==-1) 
				return; 
			switch(keyCode) { 
		    	case 13: 
		    		addEntry(dataTable.childNodes[0].childNodes[currentSelection].childNodes[0].getAttribute('id'));
		    		break; 
			}
		}
		
		highlightSuggest = function (highlightRow) { highlightRow.css('background-color','#CCCCFF');}
		unhighlightSuggest = function (highlightRow) { highlightRow.css('background-color','#F4F4FF');}
		
		function log(str) {
		  // gel("logger").html(gel("logger").html() + str+'<br>');
		}
		
		var simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		
		showProfitChart = function() {
			
			if(gel('chartContent').css('display')=='none')
			{
				gel('chartContent').html('Loading your profit chart.. Please wait..');
				gel('chartContent').css('display', '');
				gel('chartHorLine').css('display', '');
			}
			else
			{
				gel('chartContent').css('display', 'none');
				gel('chartHorLine').css('display', 'none');
				return;
			}
			var chartData = ['s:'];
			var legendData = [''];
			var colorData = [''];
			var amounts = new Array();
			var values = new Array();
			var symbols = new Array();
			var maxValue = 0;
			var maxAmountValue = 0;
			for (var i=0; i<stockTickers.length; i++)
			{
				if(stockTickers[i].numshares==0)
					continue;
				var val = 100*(stockTickers[i].price-stockTickers[i].buyprice)/stockTickers[i].buyprice;		
				val = roundNumber(val);
				val = round2Decimals(val);
				values.push(val);
				symbols.push(stockTickers[i].symbol);
				if(Math.abs(val)>maxValue)
					maxValue = Math.abs(val);
				var amount = stockTickers[i].numshares*stockTickers[i].buyprice;		
				amount = roundNumber(amount);
				amount = round2Decimals(amount);
				amounts.push(amount);
				if(Math.abs(amount)>maxAmountValue)
					maxAmountValue = Math.abs(amount);		
			}
			for (var i=0; i<values.length; i++) {
				var currentValue = amounts[i];
				currentValue = Math.abs(currentValue);
				if (!isNaN(currentValue) && currentValue >= 0) {
					chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) * currentValue / maxAmountValue)));
				}
				else {
					chartData.push('_');
				}
				
				if(i==0) {
					legendData.push(symbols[i]+'('+values[i]+'%)');
					if(values[i]<0)
						colorData.push(convertToHex(values[i], maxValue)+'0000');
					else
						colorData.push('00'+convertToHex(values[i], maxValue)+'00');
				}
				else {
					legendData.push('|'+symbols[i]+'('+values[i]+'%)');
					if(values[i]<0)
						colorData.push(','+convertToHex(values[i], maxValue)+'0000');
					else
						colorData.push(','+'00'+convertToHex(values[i], maxValue)+'00');
				}
					
			}
			
			var html = 'You do not have any stocks in your portfolio. Please edit your portfolio by adding the number of shares purchased and price paid for the stocks you own and then try again';
			if(values.length!=0)	
			{
				returnVal = '&chd='+chartData.join('')+'&chl='+legendData.join('')+'&chco='+colorData.join('');
				var url = 'http://chart.apis.google.com/chart?cht=p&chs=320x100&chco=00ff00'+returnVal;
				var imgobj = new Image();
				imgobj.src = url;
				imgobj.onload = function(){
					html = '<img border="0" src="'+imgobj.src+'" alt="Your Portfolio Chart" />';
					gel('chartContent').html(html);	
						
				}
				imgobj.onerror = function(){
					html = 'Sorry, Unable to load your portfolio chart at this time. Please try again later.';
					gel('chartContent').html(html);	
						
				}		
			}
			else
				gel('chartContent').html(html);	
				
		}
		
		function convertToHex(value, maxValue) { 	
			var val = 255-(Math.abs(value)*153/maxValue);	
			return Math.round(val).toString(16);
		}
		
		function loadSettings() {
			$("#inputRefreshRate > select").val(localStore.getItem("refreshrate"));
			$("#inputShowCharts > select").val(localStore.getItem("showchart"));
			$("#inputShowStockName > select").val(localStore.getItem("showname"));
			$("#inputHighlighting > select").val(localStore.getItem("flashing"));
			//console.log("loading settings from storage");
		}
		
		function saveSettings() {
			localStore.setItem("refreshrate", $("#inputRefreshRate > select").val());
			localStore.setItem("showchart", $("#inputShowCharts > select").val());
			localStore.setItem("showname", $("#inputShowStockName > select").val());
			localStore.setItem("flashing", $("#inputHighlighting > select").val());
			//console.log("saved settings to storage");
			initWidget();
			paintStockTicker();
		}
		
		if(userId==null) {
			initWidget();
			paintStockTicker();
		} else {
			getUserPrefs(function() {
				initWidget();
				paintStockTicker();
			});
			$("#fullscreen").attr("href", "http://udaysasi-gadgets.googlecode.com/svn/trunk/quickStockWatch.html?subscriptionid="+userId);
		}
		 
		
		$("#tickeraddbtn").click(addStockTicker);
		$("#newsbtn").click(showNewsContent);
		$("#view").click(toggleView);
		$("#strengthbtn").click(showStrengthContent);
		$("#profitChart").click(showProfitChart);
		$("#emailbtn").click(showEmailContent);
		$("#settingsloadbtn").click(loadSettings);
		$("#settingssavebtn").click(saveSettings);
		$("#deletesavebtn").click(confirmDeleteModal);
		
		$("#problememail").click(function() {
			var sub = "Problem report on Quick Stock Watch";
			var body = "I am having problems using the gadget. %0A%0A"+debugBuf.join(",")+"%0A%0A"+navigator.appVersion;
			window.open("mailto:udaysasi+feedback@gmail.com?subject="+sub+"&body="+body);
		})

		autocomplete = $('#ticker').typeahead({source: []})
        	.on('keyup', function(ev){
	            ev.stopPropagation();
	            ev.preventDefault();
            	if( $.inArray(ev.keyCode,[40,38,9,13,27]) === -1 ){
                	var self = $(this);
                	self.data('typeahead').source = [];
 	               	if( !self.data('active') && self.val().length > 0){
	                    self.data('active', true);
	                    //console.log("Locked for further inputs");
	                    searchTicker();
    	            } 
            	}
 	                         
        });
	});
	</script>
</body>
</html>